from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

"""
1.把openid保存起来
    openid是此网站上唯一对应用户身份的标识,
    网站可将此ID进行存储便于用户下次登陆时辨识其身份,
    或将其与用户在网站上的原有账号进行绑定
    
2.oauth认证的流程
    ① 获取Authorization code;
    ② 通过Authorization code获取Access Token
    
3.我们要做的
    
    按照文档来
        ①申请appid和appkey
            QQ_CLIENT_ID = '101518219'

            QQ_CLIENT_SECRET = '418d84ebdc7241efb79536886ae95224'
            
            QQ_REDIRECT_URI = 'http://www.meiduo.site:8000/oauth_callback'
    
        ②放置'QQ登陆'按钮
        
        ③拼接生成的url(看文档来拼接)
            https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test_
            可以直接拼接
            最好像新浪一样做一个ajax请求,让前端发送请求,后端返回url
        
        ④oauth认证的流程
             ④.①通过code换取token
             ④.②通过token换取openid
    
"""
from QQLoginTool.QQtool import OAuthQQ
from meiduo_mall import settings


class OauthQQLoginURLView(View):
    def get(self, request):
        state = 'test'
        # 1.创建实例
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)
        # 2.调用实例对象
        login_url = qq.get_qq_url()

        # return http.JsonResponse({
        #                              'login_url': 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101518219&redirect_uri=http://www.meiduo.site:8000/oauth_callback&state=test'})
        return http.JsonResponse({'login_url': login_url})
class OauthQQUserView(View):
    def get(self,request):
        state=request.GET.get('state')
        code=request.GET.get('code')
        if code is None:
            return http.HttpResponseBadRequest('参数有误')
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state=state)
        token=qq.get_access_token(code)
        openid=qq.get_open_id(token)

        return render(request,'oauth_callback.html')